import { atomWithProxy } from 'jotai-valtio';
import { proxy, subscribe } from 'valtio';

export interface UserStore {
  username?: string;
  token?: string;
  avatar?: string;
  background?: string;
}

// 初始化userProxy
const initUserProxy = (): UserStore => {
  const userInfo = localStorage.getItem('userInfo');
  return userInfo ? JSON.parse(userInfo) : {};
};

export const userProxy = proxy<UserStore>(initUserProxy());

// 登录状态
export const loginProxy = (info: UserStore) => {
  const { username, token, avatar, background } = info;
  userProxy.token = token;
  userProxy.username = username;
  userProxy.avatar = avatar;
  userProxy.background = background;
};

// 登出状态
export const logoutProxy = () => {
  userProxy.token = undefined;
  userProxy.username = undefined;
  userProxy.avatar = undefined;
  userProxy.background = undefined;
};

// 每当userProxy改变时候就将内容保存到本地
subscribe(userProxy, () => {
  localStorage.setItem('userInfo', JSON.stringify(userProxy));
});

export default atomWithProxy(userProxy);
